//
//  ChutianPlusViewController.m
//  suRead
//
//  Created by lidi on 2018/11/29.
//  Copyright © 2018 bao. All rights reserved.
//

#import "ChutianPlusViewController.h"
#import "Masonry.h"
#import "UIViewController+HUD.h"
#import "UIControl+Blocks.h"
#import "MJRefresh.h"
#import "ServiceSubscribe.h"
#import "ServiceNews.h"
#import "M_News.h"
#import "AccountManager.h"
#import "SubscribeNewsCell.h"
#import "UIViewController+EmptyDataSet.h"
#import "SubscribeMyListViewController.h"
#import "SubscribeClassifyViewController.h"
#import "SubscribeNewsDetailViewController.h"
#import "NewCellManager.h"
#import "SubscribeRecommandCell.h"
#import "SubscribeNewsListViewController.h"
#import "M_Subscribe.h"

@interface ChutianPlusViewController ()<UITableViewDataSource,UITableViewDelegate,UIGestureRecognizerDelegate>
@property (nonatomic,strong)UITableView *infoTableView;
@property (nonatomic,strong)NSMutableArray *infoDataArray;
@property (nonatomic,strong)NSURLSessionDataTask *requestHandle;
@property (nonatomic,assign)NSInteger currentPageIndex;
@property (nonatomic,strong)NSArray *service_item;
@property (nonatomic,strong)SubscribeRecommandCell *cellHandle;
@end

@implementation ChutianPlusViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBarHidden = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    // enable slide-back
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
        self.navigationController.interactivePopGestureRecognizer.delegate = self;
    }
    
    __weak typeof(self) weak_self = self;
    
    //头部导航栏
    UIView *navigationBarView = [UIView new];
    navigationBarView.backgroundColor = [[UIColor alloc] initWithRed:190.0f / 255.0f green:30.0f / 255.0f blue:30.0f / 255.0f alpha:1];
    [self.view addSubview:navigationBarView];
    [navigationBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(navigationBarView.superview);
        if (iPhoneX) {
            make.height.equalTo(@88.0f);
        } else {
            make.height.equalTo(@64.0f);
        }
    }];
    
    UIView *topBarView = [UIView new];
    topBarView.backgroundColor = [UIColor clearColor];
    [navigationBarView addSubview:topBarView];
    [topBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(topBarView.superview);
        if (iPhoneX) {
            make.top.equalTo(topBarView.superview).offset(44.0f);
        } else {
            make.top.equalTo(topBarView.superview).offset(20.0f);
        }
        make.height.equalTo(@44.0f);
    }];
    
    UIImageView *banner = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"banner_ctplus"]];
    [topBarView addSubview:banner];
    [banner mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(banner.superview).offset(15.0);
        make.centerY.equalTo(banner.superview);
        make.size.mas_equalTo(CGSizeMake(75, 27.5));
    }];
    
    //更多订阅
    UIButton *buttonMore = [UIButton buttonWithType:UIButtonTypeCustom];
    [buttonMore setTitle:@"更多订阅" forState:UIControlStateNormal];
    buttonMore.titleLabel.font = [UIFont fontWithName:@"FZBIAOYSJW--GB1-0" size:17.0f];
    [buttonMore setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [buttonMore addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
        SubscribeClassifyViewController *controller = [SubscribeClassifyViewController new];
        [weak_self showViewController:controller sender:nil];
    }];
    [topBarView addSubview:buttonMore];
    [buttonMore mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(buttonMore.superview);
        make.right.equalTo(buttonMore.superview).offset(-15.0f);
    }];
    
    UIView *line = [UIView new];
    [topBarView addSubview:line];
    line.backgroundColor = [UIColor whiteColor];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(buttonMore.mas_left).offset(-15.0f);
        make.width.equalTo(@1.0f);
        make.height.equalTo(@25.0f);
        make.centerY.equalTo(line.superview);
    }];
    
    //我的订阅
    UIButton *buttonCover = [UIButton buttonWithType:UIButtonTypeCustom];
    [buttonCover setTitle:@"我的订阅" forState:UIControlStateNormal];
    buttonCover.titleLabel.font = [UIFont fontWithName:@"FZBIAOYSJW--GB1-0" size:17.0f];
    [buttonCover setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [buttonCover addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
        if ([AccountManager sharedAccountManager].f_isLogined) {
            SubscribeMyListViewController *controller = [SubscribeMyListViewController new];
            [weak_self showViewController:controller sender:nil];
        } else {
            //需要登录
            UIStoryboard *personalCenterStoryBoard = [UIStoryboard storyboardWithName:@"PersonalCenter" bundle:[NSBundle mainBundle]];
            UIViewController *controller = [personalCenterStoryBoard instantiateViewControllerWithIdentifier:@"LoginViewController"];
            controller.hidesBottomBarWhenPushed = YES;
            [self showViewController:controller sender:nil];
        }
    }];
    [topBarView addSubview:buttonCover];
    [buttonCover mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(buttonCover.superview);
        make.right.equalTo(line.mas_left).offset(-15.0f);
    }];

    self.infoTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.infoTableView.dataSource = self;
    self.infoTableView.delegate = self;
    [self.view addSubview:self.infoTableView];
    [self.infoTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.infoTableView.superview);
        if (@available(iOS 11.0, *)) {
        make.top.equalTo(self.infoTableView.superview.mas_safeAreaLayoutGuideTop).mas_offset(44.0f);
        } else {
        make.top.equalTo(self.infoTableView.superview).mas_offset(64.0f);
        }
    }];
    self.infoTableView.tableFooterView = [UIView new];
    self.infoTableView.backgroundColor = [UIColor whiteColor];
    self.infoTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.infoTableView registerNib:[UINib nibWithNibName:@"SubscribeNewsCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"SubscribeNewsCell"];
    [self.infoTableView registerClass:[SubscribeRecommandCell class] forCellReuseIdentifier:@"SubscribeRecommandCell"];
    
    self.infoTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //刷新数据
        [weak_self refreshDatas];
    }];
    
    self.infoTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weak_self loadMore];
    }];
    
    [self.infoTableView.mj_header beginRefreshing];
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    return YES;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self setNeedsStatusBarAppearanceUpdate];
    
    //2016-6-22 sah hold left menu viewDidAppear
    NSString* myopen = [AppDelegate sharedAppDelegate].myOpen;
    if([myopen isEqual:@"1"]) {
        //师爱华 -2016-6-22
        [AppDelegate sharedAppDelegate].myOpen=@"0";
        //[[AppDelegate sharedAppDelegate].sideMenuViewController presentLeftMenuViewController];
    }
    
}

- (void)refreshDatas
{
    [self emptyDataSetClearAllNotice];
    [self.infoTableView.mj_footer resetNoMoreData];
    
    self.currentPageIndex = 1;
    if (self.requestHandle) {
        [self.requestHandle cancel];
        self.requestHandle = nil;
    }
    
    self.cellHandle = nil;
    
    __weak typeof(self) weak_self = self;
    NSString *uid = [AccountManager sharedAccountManager].f_uid;
    if (![AccountManager sharedAccountManager].f_isLogined) {
        uid = @"";
    }
    [ServiceSubscribe doFetchServiceList:uid pageindex:self.currentPageIndex pagesize:DEFAULT_PAGE_SIZE success:^(id  _Nonnull responseObject, NSString * _Nonnull message) {
        [weak_self.infoTableView.mj_header endRefreshing];
        weak_self.infoDataArray = [NSMutableArray array];
        NSArray *list = [responseObject objectForKey:@"list"];
        [weak_self.infoDataArray addObjectsFromArray:list];
        
        NSArray *services = [responseObject objectForKey:@"service_item"];
        if (services && [services isKindOfClass:[NSArray class]]) {
            self.service_item = services;
        } else {
            self.service_item = [NSArray array];
        }
        
        [weak_self.infoTableView reloadData];
    } failure:^(NSString * _Nonnull message) {
        [weak_self.infoTableView.mj_header endRefreshing];
        [weak_self showHUDText:message];
        //重连
//        if (!weak_self.infoDataArray || ![weak_self.infoDataArray count]) {
//            [weak_self emptyDataSetShowNetWorkAvaliable:^{
//                [weak_self.infoTableView.mj_header beginRefreshing];
//            }];
//        }
    }];
}

- (void)loadMore
{
    self.currentPageIndex ++;
    if (self.requestHandle) {
        [self.requestHandle cancel];
        self.requestHandle = nil;
    }
    
    __weak typeof(self) weak_self = self;
    NSString *uid = [AccountManager sharedAccountManager].f_uid;
    if (![AccountManager sharedAccountManager].f_isLogined) {
        uid = @"";
    }
    [ServiceSubscribe doFetchServiceList:uid pageindex:self.currentPageIndex pagesize:DEFAULT_PAGE_SIZE success:^(id  _Nonnull responseObject, NSString * _Nonnull message) {
        [weak_self.infoTableView.mj_footer endRefreshing];
        NSArray *list = [responseObject objectForKey:@"list"];
        if (list && [list isKindOfClass:[NSArray class]] && [list count] > 0) {
            [weak_self.infoDataArray addObjectsFromArray:list];
        } else {
            [weak_self.infoTableView.mj_footer endRefreshingWithNoMoreData];
        }
        
        [weak_self.infoTableView reloadData];
    } failure:^(NSString * _Nonnull message) {
        [weak_self.infoTableView.mj_footer endRefreshing];
        [weak_self showHUDText:message];
    }];
}

#pragma mark tableViewDatasouce Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        if (self.service_item) return 1; else return 0;
    } else return [self.infoDataArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (!self.cellHandle) {
            self.cellHandle = [tableView dequeueReusableCellWithIdentifier:@"SubscribeRecommandCell"];
            __weak typeof(self) weakSelf = self;
            [self.cellHandle refresh:self.service_item handle:^(NSInteger index) {
                SubscribeNewsListViewController *controller = [SubscribeNewsListViewController new];
                M_Subscribe *sub = [M_Subscribe new];
                sub.f_wid = [[[weakSelf.service_item objectAtIndex:index] objectForKey:@"wid"] integerValue];
                controller.sub = sub;
                [weakSelf showViewController:controller sender:nil];
            } moreHandle:^{
                SubscribeClassifyViewController *controller = [SubscribeClassifyViewController new];
                [weakSelf showViewController:controller sender:nil];
            }];
        }
        return self.cellHandle;
    } else {
        M_News *news = [self.infoDataArray objectAtIndex:indexPath.row];
        SubscribeNewsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SubscribeNewsCell"];
        cell.newsData = news;
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 180;
    } else {
        return 100;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 1) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        
        M_News *news_ = [self.infoDataArray objectAtIndex:indexPath.row];
        SubscribeNewsDetailViewController *controller = [SubscribeNewsDetailViewController new];
        
        NSString *uid = @"";
        if ([AccountManager sharedAccountManager].f_isLogined) {
            uid = [AccountManager sharedAccountManager].f_uid;
        }
        controller.urlString = [NSString stringWithFormat:@"%@&aid=%@&userid=%@&type=%@&wid=%@",url_service_wid_info,news_.f_id,uid,news_.f_type,news_.f_wid];
        controller.f_thumbnail = news_.f_thumbnail;
        controller.hidesBottomBarWhenPushed = YES;
        [self showViewController:controller sender:nil];
        
        //增加浏览量
        [ServiceNews doSendRead:news_.f_id success:nil failure:nil];
        
        //保存阅读记录
        [[NewCellManager shared] saveReadHistory:news_.f_id];
        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    }
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleDefault;
}

@end
